package com.huawei.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import com.huawei.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 验证token是否合法
 */
@Component
public class ValidateJwtTokenFilter extends OncePerRequestFilter {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String requestURI = request.getRequestURI();
        //对登录放行
        if (requestURI.endsWith("/login") || requestURI.endsWith("/captcha/getCaptcha")) {
            filterChain.doFilter(request, response);
            return;
        }
        //访问的时其他资源，获取token
        //String jwtToken = request.getHeader("authorization");
        String jwtToken = request.getHeader("token");
        //访问资源没有带token
        if (null == jwtToken) {
            BaseResult result = new BaseResult(-1, "token不能为空");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return;
        }

        //校验token的合法性
        //去除
        //jwtToken = jwtToken.replaceAll("Bearer ","");
        //System.out.println("jwtToken = " + jwtToken);
        //boolean flag = JwtUtil.verifyToken(jwtToken);
        ////token不合理
        //if(!flag){
        //    BaseResult result = new BaseResult(-1,"token已过期或非法");
        //    response.getWriter().write(objectMapper.writeValueAsString(result));
        //    return;
        //}
        //token合理
        //判断用户是否已经 退出
        //Boolean redisTokenIsExist = stringRedisTemplate.hasKey("jwt:" + jwtToken);
        String userJson = stringRedisTemplate.opsForValue().get("token:" + jwtToken);
        if (userJson == null) {
            BaseResult result = new BaseResult(-1, "已经退出登录");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return;
        }

        //续约token 5分钟
        stringRedisTemplate.expire("token:" + jwtToken, 5, TimeUnit.MINUTES);

        //保存认证信息
        SecurityContext context = SecurityContextHolder.getContext();
        //解析userJson中的用户信息
        User user = objectMapper.readValue(userJson, User.class);
        UsernamePasswordAuthenticationToken authToken =
                new UsernamePasswordAuthenticationToken(user, user.getUsername(), user.getAuthorities());
        context.setAuthentication(authToken);
        filterChain.doFilter(request, response);
        ////保存认证信息
        //SecurityContext context = SecurityContextHolder.getContext();
        ////获取userid
        //Integer userId = JwtUtil.getUserId(jwtToken);
        ////获取username
        //String username = JwtUtil.getUsername(jwtToken);
        ////获取权限
        //List<String> authoritityList= JwtUtil.getAuthorities(jwtToken);
        //SysUser sysUser = new SysUser(userId,username,authoritityList);
        //UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysUser,sysUser
        // .getUsername(),sysUser.getAuthorities());
        //context.setAuthentication(token);
        //filterChain.doFilter(request,response);
    }

}
